package dian.qing.li.demo.security.config.security;

import com.alibaba.fastjson.JSON;
import dian.qing.li.demo.security.commons.RestResult;
import dian.qing.li.demo.security.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拒绝访问
 *
 * @author: liqingdian
 **/
@Slf4j
public class AppAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.error(e.getMessage(), e);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        PrintWriter out = response.getWriter();
        RestResult failed = RestResult.failed(HttpServletResponse.SC_FORBIDDEN, "权限不足", null);
        out.write(JSON.toJSONString(failed, Constants.FASTJSON_SERIALIZER));
        out.flush();
        out.close();
    }
}
